#include <muduo/net/TcpServer.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <unordered_map>
#include <functional>

using namespace std;



class DictSever
{
private:
    muduo::net::TcpServer _sever;
    muduo::net::EventLoop _baseloop;
public:
    DictSever(int port)
    :_sever(&_baseloop,muduo::net::InetAddress("0.0.0.0",port),"dictSever",muduo::net::TcpServer::kNoReusePort)
    {
        //调用我写的回调
        _sever.setConnectionCallback(bind(&DictSever::onConnection,this,placeholders::_1));
        _sever.setMessageCallback(bind(&DictSever::onMessageConn,this,placeholders::_1,placeholders::_2,placeholders::_3));
    }

    void Start()
    {
        _sever.start();  //开启监听
        _baseloop.loop(); //开启循环
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            cout << "连接成功！" << endl;
        }
        else
        {
            cout << "连接失败" << endl;
        }
    }

    void onMessageConn(const muduo::net::TcpConnectionPtr& conn,muduo::net::Buffer* buff,muduo::Timestamp receiveTime)
    {
        unordered_map<string,string> dicthash = { {"hello","你好"},{"world","世界"}};

        //读发过来的buff缓冲区的所有信息
        string msg = buff->retrieveAllAsString();

        string ret;
        auto it = dicthash.find(msg);
        if(it != dicthash.end())
        {
            ret = it->second;
        }
        else
        {
            ret = "未知单词";
        }

        conn->send(ret);
    }
};


int main()
{
    DictSever dictsever(8888);

    dictsever.Start();
}